package com.ly.lypopupwindowdemo.views;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

/**
 * Created by liying on 2017/5/18.
 * 自定义控件学习之一
 * 自绘控件即View上所展现的内容全部都是我们自己绘制出来的
 * 自定义一个计数器View，这个View可以响应用户的点击事件，并自动记录一共点击了多少次
 */

public class CountView extends View implements View.OnClickListener{
    private Paint mPaint;
    private Rect mBounds;
    private int mCount;

    public CountView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mBounds = new Rect();
        setOnClickListener(this);//构造方法里设置监听，这样每次点击控件的时候就会调用onClick（）方法
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        mPaint.setColor(Color.BLUE);//将画笔设置成蓝色
        canvas.drawRect(0,0,getWidth(),getHeight(),mPaint);//画一个矩形
        mPaint.setColor(Color.YELLOW);//又将画笔设置为黄色
        mPaint.setTextSize(30);
        String text = String.valueOf(mCount);
        mPaint.getTextBounds(text,0,text.length(),mBounds);//获取文字的宽度和高度
        float textWidth = mBounds.width();
        float textHeight = mBounds.height();
        canvas.drawText(text, getWidth() / 2 - textWidth / 2, getHeight() / 2
                + textHeight / 2, mPaint);//调用了drawText()方法去进行绘制就可以了。

    }

    @Override
    public void onClick(View v) {

        mCount++;
        invalidate();//重绘视图
    }
}
